<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Log;
use app\common\model\Log as ModelLog;
use app\common\model\Order;
use app\common\model\order\Info;
use app\common\model\Store;
use app\common\model\User;
use think\Cache;
use think\Db;

/**
 * 微信支付接口
 */
class Wechat extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    /**
     * 支付成功回调
     */
    //微信回调
    public  function notify()
    {
        $data = file_get_contents('php://input');
        $data = json_decode($data, true);
        Log::write($data);
        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        //php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            //$APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, config('site.apiv3_private_key'));
            // $orderData ='{"mchid":"1600729506","appid":"wx9290cdf0e8a69b12","out_trade_no":"MS202208251730181304","transaction_id":"4200001589202208269945980187","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"bb","success_time":"2022-08-26T18:15:40+08:00","payer":{"openid":"o5CYT5N5fuZ3CV5qyfK3EKPsxVnM"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}}';
            $orderData = json_decode($orderData, true);
            if ($orderData['trade_state'] == 'SUCCESS') {
                $order_sn = $orderData['out_trade_no']; //商户订单号
                $transaction_id = $orderData['transaction_id']; //微信订单号
                $attach = $orderData['attach'];
                // 启动事务
                Db::startTrans();
                try {
                    /*业务处理*/
                    switch ($attach) {
                        case 'order':
                            $order = Order::get(['sn' =>  $order_sn, 'status' => 0]);
                            if ($order) {
                                $order->save(['status' => 1, 'paytime' => time()]);
                            }
                            break;
                    }
                    Db::commit();
                    //应答微信支付已处理该订单的通知
                    Log::info(json_encode($orderData));
                    return;
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    Log::error('错误：', $e->getMessage());
                    return $e->getMessage();
                }
            }
        }
    }
    //退款回调地址
    public static function refund_notify()
    {
        $notifiedData = file_get_contents('php://input');
        $data = json_decode($notifiedData, true);
        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        //php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            //$APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, config('site.apiv3_private_key'));
            $orderData = json_decode($orderData, true);
            if ($orderData['refund_status'] == 'SUCCESS') {
                $transaction_id = $orderData['transaction_id']; //退款单号
                // Order::where('transaction_id',  $transaction_id)->update(['order_status' => 3]);
                /*业务处理*/
                return json(['code' => 'SUCCESS', 'message' => '成功']);
            }
        }
    }
   
}
